package com.springcloud.controller;

import com.springcloud.entities.CommonResult;
import com.springcloud.entities.Payment;
import com.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
//下面这个注解的作用我还不是很清楚
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    //对于注册进eureka里面的服务，我们有一个需求，这个需求就是：
    //我们要通过注册中心，来看到这个服务的信息，比如地址啦什么的
    //下面的这个注入的对象就是这个作用
    //我们可以通过服务发现来获取该服务的信息
    @Resource
    private DiscoveryClient discoveryClient;
    //上面的这个包很容易引错，一定要是上面的才行

    @GetMapping("/payment/get/{id}")
    @ResponseBody
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        if (payment!=null){
            return new CommonResult(200,"查询数据成功,server.port:"+serverPort,payment);
        }else{
            return new CommonResult(500,"查询数据是空",null);

        }
    }

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);

        //log.info("插入成功"+result);

        if (result>0){
            return new CommonResult(200,"插入数据成功,server.port:"+serverPort,result);

        }else{
            return new CommonResult(500,"插入数据失败",null);

        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        //得到我们的服务清单列表，盘点一下家底，这个还是需要我认真的理解一下的
        List<String> services = discoveryClient.getServices();
        for (String service:services) {
            log.info("*******service"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLb(){
        return serverPort;
    }

    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try{
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return serverPort;
    }



}